package domain

import (
	"errors"
	"fmt"
	"gitee.com/sunny-zhangqiang/zcache/service/loadbalance"
	"regexp"
)

const (
	OriginLineTypeIP     = 1
	OriginLineTypeDomain = 2
)

const (
	OriginLineTag = "config_origin_line"
)

const (
	OriginSchemeHttp  = "http"
	OriginSchemeHttps = "https"
)

type OriginLine struct {
	Type                int
	Host                string
	Port                int
	Weight              int
	MaxFails            int
	MaxLineFails        int
	MaxFailedTimeoutSec int
}

type OriginConfig struct {
	MainLines   []OriginLine
	BackupLines []OriginLine

	//EnableHash          bool
	//HashKey             string
	MaxRetry            int
	RandomPickInAllDone bool
	Follow302           bool
	Scheme              string // 回源协议
	Host                string // 回源Host

	mainEndpointPool   *loadbalance.EndpointPool
	backupEndpointPool *loadbalance.EndpointPool
}

func (conf *OriginConfig) GetMainEndpointPool() *loadbalance.EndpointPool {
	return conf.mainEndpointPool
}

func (conf *OriginConfig) GetBackupEndpointPool() *loadbalance.EndpointPool {
	return conf.backupEndpointPool
}

type PathConfig struct {
	Path string

	EnableSlice  bool
	FragmentSize int

	OriginConfig *OriginConfig

	regex *regexp.Regexp
}

type Domain struct {
	Version     int64
	*PathConfig // default path config
	Path        []*PathConfig
}

func CheckAndFixPathConf(conf *PathConfig) error {
	if conf == nil {
		return errors.New("invalid path config")
	}

	if conf.EnableSlice {
		if conf.FragmentSize == 0 {
			conf.FragmentSize = 1 << 20
		}

		if conf.FragmentSize&(conf.FragmentSize-1) != 0 {
			return fmt.Errorf("the conf.FragmentSize must be a power of 2")
		}
	}

	return nil
}

func CheckAndFixDomainConf(conf *Domain) error {
	for _, v := range conf.Path {
		regex, err := regexp.Compile(v.Path)
		if err != nil {
			return err
		}
		v.regex = regex
	}

	return nil
}
